//
//  XZHHomeNoteTableViewCell.m
//  Piece
//
//  Created by dllo on 16/6/20.
//  Copyright © 2016年 Northeast Dianli University. All rights reserved.
//

#import "XZHHomeNoteTableViewCell.h"
#import "UIImageView+WebCache.h"
#import "FLWeatherView.h"
#import "FLWeatherInfo.h"
#import <CoreLocation/CoreLocation.h>
#import "Masonry.h"
#import "JTSImageInfo.h"
#import "JTSImageViewController.h"

#define TIMER_INTERVAL_IN_SEC 45.0
#define WEATHER_UPDATE_INTERVAL_IN_MINUTE 30
#define OPEN_WEATHER_MAP_URL @"http://api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&appid=58779be4c7b736be1a7af6666440c628"

#define IOS8 ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0)

@interface XZHHomeNoteTableViewCell ()<CLLocationManagerDelegate, UITextViewDelegate>
@property (strong, nonatomic) NSTimer *timer;
@property (assign, nonatomic) NSInteger timerFireCount;
@property (strong, nonatomic) CLLocationManager *locationManager;

@property (weak, nonatomic) FLWeatherView *weatherView;

@end

@implementation XZHHomeNoteTableViewCell{
    UILabel *locationLabel;
}


- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapImageView:)];
    [self.coverImageView addGestureRecognizer:tapGesture];
    self.coverImageView.userInteractionEnabled = YES;
    
    self.contentsView.layer.cornerRadius = 5;
    self.contentsView.layer.borderColor = [UIColor colorWithRed:0.86 green:0.87 blue:0.88 alpha:0.8].CGColor;
    self.contentsView.layer.cornerRadius = 5;
    self.contentsView.layer.borderWidth = 2;
    self.contentLabel.delegate = self;
//    self.contentLabel.editable = NO;
//    self.contentLabel.scrollEnabled = NO;
    
    
#pragma mark 实时监测天气
    _timerFireCount = 0;
    
    _locationManager = [[CLLocationManager alloc] init];
    _locationManager.delegate = self;
    _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    _locationManager.distanceFilter = 10.0f;
    if (IOS8) {
        [_locationManager requestAlwaysAuthorization];
    }
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:TIMER_INTERVAL_IN_SEC target:self selector:@selector(timerUp) userInfo:nil repeats:YES];
    [_timer fire];
    
    FLWeatherView *weatherView = [[FLWeatherView alloc] init];
    weatherView.frame = CGRectMake(self.timeLabel.frame.origin.x, self.coverImageView.frame.origin.y + self.coverImageView.frame.size.height + 5, 200, 70);
    [self.contentView addSubview:weatherView];
    self.weatherView = weatherView;
    
    locationLabel = [[UILabel alloc] init];
    locationLabel.text = @"北京市";
    locationLabel.font = [UIFont systemFontOfSize:12];
    locationLabel.textColor = [UIColor colorWithRed:0.72 green:0.72 blue:0.72 alpha:1.00];
    [self.contentView addSubview:locationLabel];
    [locationLabel makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weatherView.right).offset(-85);
        make.top.equalTo(weatherView).offset(4);
        make.height.equalTo(70);
        make.width.equalTo(100);
    }];

}

#pragma mark 发送请求获得天气数据
- (void)updateCityWeatherInfoWithCoordinate:(CLLocationCoordinate2D) coordinate {
    NSString *path = [NSString stringWithFormat:OPEN_WEATHER_MAP_URL, coordinate.latitude, coordinate.longitude];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:path]];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError) {
            
        }else {
            NSDictionary *resultDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSString *icon = resultDict[@"weather"][0][@"icon"];
            NSString *temp = [NSString stringWithFormat:@"%@", resultDict[@"main"][@"temp"]];
            
            FLWeatherInfo *info = [FLWeatherInfo infoWithIcon:icon temperature:temp];
            //            FLWeatherInfo *info = [FLWeatherInfo infoWithIcon:@"00" temperature:@"12"];
            
            
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                self.weatherView.info = info;
            }];
        }
    }];
}

- (void)timerUp {
    //    [_weatherView setTimeWithDate:[NSDate date]];
    //
    //    _timerFireCount++;
    //    if (_timerFireCount * TIMER_INTERVAL_IN_SEC > WEATHER_UPDATE_INTERVAL_IN_MINUTE * 60) {
    //        _timerFireCount = 0;
    [self updateWeather];
    //    }
}

- (void)updateWeather {
    [_locationManager startUpdatingLocation];
}

#pragma mark 定位
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
        
    }else {
        [self updateWeather];
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *curLocation = [locations lastObject];
    [self updateCityWeatherInfoWithCoordinate:curLocation.coordinate];
    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:curLocation completionHandler:^(NSArray *array, NSError *error){
        if (array.count > 0){
            CLPlacemark *placemark = [array objectAtIndex:0];
            //将获得的所有信息显示到label上
            //获取城市
            NSString *city = placemark.locality;
            if (!city) {
                //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                city = placemark.administrativeArea;
            }
            
            locationLabel.text = city;
        }
        else if (error == nil && [array count] == 0)
        {
            NSLog(@"No results were returned.");
        }
        else if (error != nil)
        {
            NSLog(@"An error occurred = %@", error);
        }
    }];
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    [manager stopUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    if ([error code] == kCLErrorDenied) {
        NSLog(@"访问被拒绝");
    }else if ([error code] == kCLErrorLocationUnknown) {
        NSLog(@"无法获取位置信息");
    }
}

-(void)setModel:(XZHHomeModel *)model
{
    if (_model != model) {
        _model = model;
        NSDate *nowDate=[NSDate date];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationAction:) name:@"照片" object:nil];
        
        NSDateFormatter * outputFormatter = [[NSDateFormatter alloc]init];
        [outputFormatter setDateFormat:@"dd MMM,yyyy.EEE"];
        NSString *str = [outputFormatter stringFromDate:nowDate];
        self.timeLabel.text = str;
        [self.delegate passDate:str];
        
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineSpacing = 10;// 字体的行间距
        NSDictionary *attributes = @{
                                     NSFontAttributeName:[UIFont systemFontOfSize:14],
                                     NSParagraphStyleAttributeName:paragraphStyle
                                     };
        self.contentLabel.attributedText = [[NSAttributedString alloc] initWithString:model.hp_content attributes:attributes];
        [self.delegate passContent:model.hp_content];
        //        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:13], NSFontAttributeName,nil];
        CGRect newRect = [model.hp_content boundingRectWithSize:CGSizeMake(ScreenWidth - 36, 8000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
        [self.contentLabel sizeToFit];
        self.contentLabel.frame = CGRectMake(self.timeLabel.frame.origin.x, self.timeLabel.frame.size.height + self.timeLabel.frame.origin.y, self.timeLabel.frame.size.width, newRect.size.height + 60);
        [self.coverImageView sd_setImageWithURL:[NSURL URLWithString:model.hp_img_url]placeholderImage:[UIImage imageNamed:@"home_cover_placeholder"]];
        self.titlesLabel.text = model.hp_title;
    }
}

- (void)setDetailModel:(XZHHomeNoteModel *)detailModel {
    if (_detailModel != detailModel) {
        _detailModel = detailModel;
        
        NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
        paragraphStyle.lineSpacing = 10;// 字体的行间距
        NSDictionary *attributes = @{
                                     NSFontAttributeName:[UIFont systemFontOfSize:14],
                                     NSParagraphStyleAttributeName:paragraphStyle
                                     };
        self.contentLabel.attributedText = [[NSAttributedString alloc] initWithString:detailModel.content attributes:attributes];
        //        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:13], NSFontAttributeName,nil];
        CGRect newRect = [detailModel.content boundingRectWithSize:CGSizeMake(ScreenWidth - 36, 8000) options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil];
        [self.contentLabel sizeToFit];
        self.contentLabel.frame = CGRectMake(self.timeLabel.frame.origin.x, self.timeLabel.frame.size.height + self.timeLabel.frame.origin.y, self.timeLabel.frame.size.width, newRect.size.height + 60);
        if ([detailModel.image isEqualToString:@"(null)"]) {
            [self.coverImageView sd_setImageWithURL:[NSURL URLWithString:detailModel.placeholderImage]placeholderImage:[UIImage imageNamed:@"home_cover_placeholder"]];
        } else {
            NSData *_decodedImageData = [[NSData alloc] initWithBase64Encoding:detailModel.image];
            UIImage *_decodedImage = [UIImage imageWithData:_decodedImageData];
            self.coverImageView.image = [UIImage imageNamed:@"home_cover_placeholder"];
            self.coverImageView.image = _decodedImage;
        }
        self.timeLabel.text = detailModel.date;
        
        self.titlesLabel.text = @"From PIECE / Self";
    }
}
#pragma mark 通知中心传照片
- (void)notificationAction:(NSNotification *)notification
{
    UIImage *image = (UIImage *)notification.object;
    self.coverImageView.image = image;
}
#pragma mark 选择照片轻拍方法
- (void)didTapImageView:(UITapGestureRecognizer *)tap {
    [self.delegate pickPhoto];
}


- (void)textViewDidEndEditing:(UITextView *)textView {
    [self.delegate passContent:self.contentLabel.text];
}

- (void)textViewDidChange:(UITextView *)textView {
    [self.delegate passContent:self.contentLabel.text];
}

#pragma mark 键盘回收
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.delegate passContent:self.contentLabel.text];
    [self.contentLabel resignFirstResponder];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
